<%@ include file="/WEB-INF/views/commonJSTL.jsp" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>FarmaSoft</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<%@ include file="/WEB-INF/views/commonResources.jsp" %>
<script src="<c:url value="/resources/js/jquery.maxlength.min.js" />"></script>

<script type="text/javascript">
var listProductAttribute = [];
var indexRow = 0;
var currentIndexRow = -1;

<c:forEach var="item" items="${listProductAttribute}">
	var productAttribute = {productAttributeId:"<c:out value="${item.productAttributeId}"/>",name:"<c:out value="${item.name}"/>",detail:"<c:out value="${item.detail}"/>",order:"<c:out value="${item.order}"/>",image:"<c:out value="${item.image}"/>"};
	listProductAttribute.push(productAttribute);
</c:forEach>

	$(document).ready(function(){
        $('div.maxLength textarea').maxlength({max:1000,slider: true}); // complete carateres on maxLength

        $("#formGrupo").validate({
	        submitHandler: function(form) {
	       		form.submit();
	        }
	    }); 
        
        $(".buttonSave").click(function(){
			var flag = $("#formGrupo").valid();
			if(flag){
				if($("#productAttributeTable tbody tr").hasClass("tr_decorado")){
					$("#formGrupo").submit();	
				}else{
					$("#requiredComp").toggleClass("noDisplay",false);
				}
			}
		});
        
	    $("#dialogoProductAttribute").dialog({autoOpen: false, height: 400, width: 680, modal: true,
				buttons: {
		            "Aceptar": function() {
		            	var flag = $("#formDialogProductAttribute").valid({
		            		rules: {
		            			 orderAttribute: {required: true, digits: true}
		            		},
			            	messages: {
			            		orderAttribute: {
			                        required: "Ingrese el orden.",
			                        digits: "Ingrese solo digitos por favor!"
			                    }
		            		}
		            	});
		                if(flag){
		            		addEditTableProductAttribute();
		                	$(this).dialog("close");
		                } 
		            },
		            Cancelar: function() {
		                $( this ).dialog( "close" );
		            }
				},
				close: function() {
					$( this ).dialog( "close" );
				}
			});
			
			$("#buttonAddProductAttri").click(function(){
				openDialogModalForm("#dialogoProductAttribute","Nuevo Producto Attributo",null); // parameters (identifier element, title form, function call back)
			});
	  
			/****************************** STARD FUNCTIONS DIALOG *******************************/
	  
			$('#productAttributeTable').on('click', '.deleteRowCarga', function () {
				$(this).parents('tr').first().remove();
				/* when we delete we have to verify that not exist a row because if exist we have to reset the array 'typesCompValuesIni' */
				if(!$("#productAttributeTable tbody tr").hasClass("tr_decorado")){
					$('#productAttributeTable thead tr').remove();
				}
			});
			/****************************** END FUNCTIONS DIALOG   *******************************/
			
			//permit only numbers
			$('.numberOnlyNumber').keyup(function () {
		         if (this.value != this.value.replace(/[^0-9]/g,'')) {
		            this.value = this.value.replace(/[^0-9]/g, '');
		         }
		     });
			
			//permit only text
			$('.lettersOnly').keyup(function () {
		         if (this.value != this.value.replace(/[^A-Za-z\s]/g, '')) {
		            this.value = this.value.replace(/[^A-Za-z\s]/g, '');
		         }
		     });
						
	}); //end ready
	
	// FUNCTION EDIT PRODUCT ATTRIBUTE
	function editProductAttribute(indexRow){
		currentIndexRow = indexRow;
		$("#isPopUpEditeProductAttribute").val("true");
		openDialogModalForm("#dialogoProductAttribute","Editar Producto Attributo",function(){
			$("#nameProductAttribute").val($("#productAttributeTable tbody #nameTD"+indexRow).text());
			$("#detailProductAttribute").val($("#productAttributeTable tbody #detailTD"+indexRow).text());
			$("#orderAttribute").val($("#productAttributeTable tbody #orderAttributeTD"+indexRow).text());
		});
	}	
	
	function addEditTableProductAttribute(){
		var textHtml = "";
		var isPopUpEdit = ($("#isPopUpEditeProductAttribute").val() == "true");
		$("#requiredComp").toggleClass("noDisplay",true);
		if(!$("#productAttributeTable tbody tr").hasClass("tr_decorado")){
			textHtml = 	"<tr>"+
						"	<th class='th_decoradoRowspan'><fmt:message key='table.name'/></th>"+
						"	<th class='th_decoradoRowspan'><fmt:message key='table.description'/></th>"+
						"	<th class='th_decoradoRowspan'><fmt:message key='table.order'/></th>"+
						"	<th class='th_decoradoRowspan' colspan='2'><fmt:message key='table.actions'/></th>"+
						"</tr>";
			$("#productAttributeTable thead").append(textHtml);
		}
		if(!isPopUpEdit){ // add new row
			textHtml = "";
			textHtml += "<tr class='tr_decorado'>"+
						"	<td class='td_decorado' id='nameTD"+indexRow+"'>"+$("#nameProductAttribute").val()+"</td>"+
						"	<td class='td_decorado' id='detailTD"+indexRow+"'>"+$("#detailProductAttribute").val()+"</td>"+
						"	<td class='td_decorado' id='orderAttributeTD"+indexRow+"'>"+$("#orderAttribute").val()+"</td>"+
						"	<td class='td_decorado' style='text-align: right'><div class='botonEditar test'><a href='javascript:editProductAttribute("+(indexRow)+")' title='Pulsa aqu&iacute; para Editar'></a></div></td>"+
	        			"	<td class='td_decorado' style='text-align: right'><div class='botonEliminar'><a href='#' class='deleteRowCarga' title='Pulsa aqu&iacute; para Eliminar'></a></div></td>"+
	        			"	<input type='hidden' name='productAttributeValues' id='productAttributeValues_"+indexRow+"' value='"+$("#nameProductAttribute").val()+"||"+$("#detailProductAttribute").val()+"||"+$("#orderAttribute").val()+"'/>";
			textHtml += "</tr>";		
			$("#productAttributeTable tbody").append(textHtml);
			indexRow++;
		}else{
			$("#productAttributeTable tbody #nameTD"+currentIndexRow).text($("#nameProductAttribute").val());
			$("#productAttributeTable tbody #detailTD"+currentIndexRow).text($("#detailProductAttribute").val());
			$("#productAttributeTable tbody #orderAttributeTD"+currentIndexRow).text($("#orderAttribute").val());
			$("#productAttributeValues_"+currentIndexRow).val($("#nameProductAttribute").val()+"||"+$("#detailProductAttribute").val()+"||"+$("#orderAttribute").val());
			$("#isPopUpEditeProductAttribute").val("false");
		}
	}

	function activeSubstanceList(){
		location.href = "configActiveSubstance?_menuId=1&_subMenuId=1&_optionId=1";	
	}

	function mainActiveSubstance(){
		location.href = "configActiveSubstance?_menuId=1&_subMenuId=1&_optionId=1";
	}
	
</script>
</head>

<body>
<div id="top-wrap">
	<%@include file="../../../head.jsp"  %>
	<div id="bodySpace">
		
	    <div class="clearfix" id="middle" style="position: absolute">  <!-- aqui va la ruta -->
	        <!-- aqui va el arbol de entrada -->
	        <div id="breadcrumb">
	            <ul>
                	<li><a href="mainFront?v=1">Home</a></li>
                        <li><span style="color:#666">Configuraci&oacute;n</span></li>
                        <li><span style="color:#666">Productos/Principio Activo</span></li>
                        <li class="current-page"><span class="end"><span class="middle">Principio Activo</span></span></li>
                </ul>
	        </div>
	    </div>
	    
	    <div id="principal">
            <!-- izquierda -->
            <div class="cuerpo2y" style="border: 0px solid"><br/><br/><!-- estos break son necesarios ya q uso absolute en css  cuerpo izquierdo-->
                <div class="izq">
					<%@include file="../../../bodyIzq.jsp" %>	
                </div>

                <div class="medio" style="border: 0px solid">
                            <div id="divForm">
                            <c:set var="varTitle" value="Nuevo"/>
                            <c:set var="actionForm" value="newActiveSubstance?_menuId=1&_subMenuId=1&_optionId=1"/>
                            <c:if test="${param._activeSubstanceId != null}">
	                            <c:set var="varTitle" value="Modificar"/>								
	                            <c:set var="actionForm" value="activeSubstanceEdit?_menuId=1&_subMenuId=1&_optionId=1"/>
							</c:if>                           
                           
                            <h2 class="decorado">${varTitle} Principio Activo (Nombre Gen&eacute;rico)</h2><br/>
                                <form method="post" id="formGrupo" action="${actionForm}">                     
                                 	<input type="hidden" name="activeSubstanceId" id="activeSubstanceId" value="${param._activeSubstanceId}">         
                                    <div style="clear:both;">
                                        <label class="form_align43">Nombre :</label>
                                        <input name="name" id="name" value="${activeSubstance.name}" class="required form_input_align lettersOnly" maxlength="30" title="Ingrese el Nombre." placeholder="letras"/>
                                        <label class="error">*</label>                                                                            
                                    </div>
                                    <div style="clear:both;">
                                        <label class="form_align43">Sinonimos :</label>
                                        <input name="synonyms" id="synonyms" value="${activeSubstance.synonyms}"  class="form_input_align lettersOnly" maxlength="150" title="Ingrese sus sinonimos." placeholder="letras"/>                                                                                                                          
                                    </div>
                                    
                                    <div style="clear:both;">
                                        <label class="form_align43">Accion terapeutica :</label>
                                        <input name="therapeuticAction" id="therapeuticAction" value="${activeSubstance.therapeuticAction}" class="required form_input_align lettersOnly" maxlength="100" title="Ingrese la accion terap&eacute;utica." placeholder="letras"/>
                                        <label class="error">*</label>                                                                                                                    
                                    </div>
                                    <div style="clear:both;">
                                        <label class="form_align43">Propiedades :</label>
                                        <div class="maxLength">
								        	<textarea name="properties" id="properties" class="required form_input_align" rows="6" cols="30" title="Ingrese sus propiedades."  placeholder="texto">${activeSubstance.properties}</textarea>
								        </div>
                                        <label class="error">*</label>                                                                                                                    
                                    </div>
                                    
                                    <br/><br/><br/>
							
									<div style="clear:both;">
										<label class="form_align43"><fmt:message key="form.attributes"/>:</label>
										&nbsp;&nbsp;<input type="button" id="buttonAddProductAttri" class="boton" value="<fmt:message key="button.add"/> <fmt:message key="title.attribute"/>" title='<fmt:message key="onclick.New"/> <fmt:message key="title.attribute"/>.'/>
										<label class="error">*</label>
									</div>
									<div style="clear:both;">							
		   	                    		<label class="form_align43"></label>
						             	<table id="productAttributeTable" class="tabla_decorado">
									     	<thead>
										     	<c:if test="${(not empty listAttribute)}" >
											     	<tr>
														<th class='th_decoradoRowspan'><fmt:message key='table.name'/></th>
														<th class='th_decoradoRowspan'><fmt:message key='table.description'/></th>
														<th class='th_decoradoRowspan'><fmt:message key='table.order'/></th>
														<th class='th_decoradoRowspan' colspan='2'><fmt:message key='table.actions'/></th>
													</tr>
												</c:if>
									     	</thead>				
									     	<tbody>
									     		<c:if test="${(not empty listAttribute)}" >
													<c:set var="j" value="1"/>
										     		<c:set var="i" value="0"/>
													<c:forEach items="${listAttribute}" var="item">
														<c:set var="valueTemp" value="${item.name}||${item.detail}||${item.order}"/>
											     		<tr class='tr_decorado'>
															<td class='td_decorado lettersOnly' id='nameTD${i}'>${item.name}</td>
															<td class='td_decorado' id='detailTD${i}'>${item.detail}</td>
															<td class='td_decorado' id='orderAttributeTD${i}'>${item.order}</td>
															<td class='td_decorado' style='text-align: right'><div class='botonEditar test'><a href='javascript:editProductAttribute("${i}")' title='Pulsa aqu&iacute; para Editar'></a></div></td>
									        				<td class='td_decorado' style='text-align: right'><div class='botonEliminar'><a href='#' class='deleteRowCarga' title='Pulsa aqu&iacute; para Eliminar'></a></div></td>
									        				<input type='hidden' name='productAttributeValues' id='productAttributeValues_${i}' value='${valueTemp}' />
														</tr>														
				                            			<c:set var="i" value="${i+j}"/>
				                            			<script type="text/javascript">
											     			indexRow++;
											     		</script>
													</c:forEach> 
												</c:if>  
									    	</tbody>
										</table>
		   	                    	</div>
									<div style="clear:both;">
		   	                    		<label class="form_align43"></label>
		   	                    		<div id="requiredComp" class="form_input_align noDisplay requeredDataTable" >Debe tener al menos un atributo <br/></div>
		    	                    	<table id="attributeTable" class="tabla_decorado">
									     	<thead>
									     	</thead>				
									     	<tbody>
									    	</tbody>
										</table>
		   	                    	</div>
		   	                    	<br/>

									<div style="clear: both">
										<label class="form_align43">&nbsp;</label>
										<table style="float: left">
											<fmt:message key="button.register" var="varSubmit" />
											<c:if test="${param._activeSubstanceId != null}">
												<fmt:message key="button.modify" var="varSubmit" />
											</c:if>			
											<tr>
												<td style="text-align:right"><br/><input type="button" value="${varSubmit}" name="action"  class="boton buttonSave" title="<fmt:message key="onclick.for"/> ${varTitle}" />&nbsp;&nbsp;</td>
												<td><br/>&nbsp;&nbsp;<input type="button" value="<fmt:message key="button.cancel"/>" name="action" onclick="mainActiveSubstance()" class="boton" title="<fmt:message key="onclick.cancel"/>"/></td>
											</tr>
										</table>
									</div>
                                </form>
                            </div>
                            
							<div id="dialogoProductAttribute"><br/>
								<form id="formDialogProductAttribute">
									<input type="hidden" name="isPopUpEditeProductAttribute" id="isPopUpEditeProductAttribute" value="false" />
									<input type="hidden" name="orderProductAttribute" id="orderProductAttribute" value="0" />
									
									<div style="clear:both;">
										<c:set var="showName" scope="page"><fmt:message key="show.form.name"/>.</c:set>		
										<label class="form_align35"><fmt:message key="form.name"/> :</label>
										<input type="text" name="nameProductAttribute" id="nameProductAttribute" value="" class="required form_input_align lettersOnly" title="${showName}" placeholder="letras"/>
										<label class="error">*</label>
									</div>
									
									<div style="clear:both;">
										<c:set var="showDetail" scope="page"><fmt:message key="show.form.detail"/>.</c:set>		
										<label class="form_align35"><fmt:message key="form.detail"/> :</label>
										<div class="maxLength">
								        	<textarea name="detailProductAttribute" id="detailProductAttribute" class="required form_input_align" rows="5" placeholder="texto"></textarea>
								        </div>
										<label class="error">*</label>
									</div>
									
									<div style="clear:both;">
										<c:set var="showOrderTitle" scope="page"><fmt:message key="show.form.order"/>.</c:set>
										<label class="form_align35"><fmt:message key="form.order"/> :</label>
										<input type="text" name="orderAttribute" id="orderAttribute" value="" maxlength="2" class="required digits form_input_align numberOnlyNumber" onkeypress="return onlyDigits(event);" placeholder="números" />
										<label class="error">*</label>
									</div>
								</form>
							</div>
                        </div>
            </div><!--end of leftPan-->
            
            <div class="yDer" style="border: 1px solid #ccc;">
                  <%@include file="../../../notices.jsp" %>                       
            </div><!--end of rightPan-->
        </div><!--end main content -->
	</div>
</div>
</body>
</html>
